package com.school.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    public void start() {
        try {
            ServerSocket serverSocket = new ServerSocket(10000);
            ExecutorService pool= Executors.newCachedThreadPool();
            InputStream inputStream = Server.class.getClassLoader().getResourceAsStream("rpc.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            while (true){
                Socket socket = serverSocket.accept();
                pool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                            String interfaceName = in.readUTF();
                            String methodName = in.readUTF();
                            Class[]paramTypes = (Class[]) in.readObject();
                            Object[] args = (Object[]) in.readObject();
                            String implClassName = properties.getProperty(interfaceName);
                            Class<?> implClass = Class.forName(implClassName);
                            Method method = implClass.getDeclaredMethod(methodName, paramTypes);
                            method.setAccessible(true);
                            Object result = method.invoke(implClass.newInstance(), args);
                            out.writeObject(result);
                            out.flush();
                            socket.close();
                        } catch (IOException | ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
                            e.printStackTrace();
                        }

                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
